package cn.edu.swu.miniwebsvr.core;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        // 1. 读取并解析 HTTP 请求行 (e.g., GET /path?param=value HTTP/1.1)
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) {
            throw new IOException("Empty request");
        }

        String[] requestParts = requestLine.split(" ");
        if (requestParts.length < 2) {
            throw new IOException("Invalid request line: " + requestLine);
        }

        String method = requestParts[0];
        String fullUrl = requestParts[1];

        parameter.setMethod(method);

        // 解析URL和查询参数
        String url;
        String queryString = "";
        int queryIndex = fullUrl.indexOf('?');
        if (queryIndex != -1) {
            url = fullUrl.substring(0, queryIndex);
            queryString = fullUrl.substring(queryIndex + 1);
        } else {
            url = fullUrl;
        }

        parameter.setUrl(url);

        // 解析URL参数
        if (!queryString.isEmpty()) {
            parseQueryString(queryString, parameter);
        }

        // 2. 循环读取并解析所有 HTTP 请求头
        String headerLine;
        while (!(headerLine = reader.readLine()).isEmpty()) {
            int colonIndex = headerLine.indexOf(':');
            if (colonIndex > 0) {
                String headerName = headerLine.substring(0, colonIndex).trim();
                String headerValue = headerLine.substring(colonIndex + 1).trim();
                parameter.addHeader(headerName, headerValue);
            }
        }

        // 3. 根据请求方法 (Method) 和请求头 (Content-Length, Content-Type) 判断并读取请求体
        if ("POST".equalsIgnoreCase(method)) {
            String contentLengthStr = parameter.getHeaders().get("Content-Length");
            String contentType = parameter.getHeaders().get("Content-Type");

            if (contentLengthStr != null) {
                int contentLength = Integer.parseInt(contentLengthStr);
                if (contentLength > 0) {
                    char[] bodyChars = new char[contentLength];
                    reader.read(bodyChars, 0, contentLength);
                    String body = new String(bodyChars);

                    // 解析application/x-www-form-urlencoded格式的请求体
                    if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
                        parseQueryString(body, parameter);
                    }
                }
            }
        }

        return parameter;
    }

    private static void parseQueryString(String queryString, Parameter parameter) {
        if (queryString == null || queryString.isEmpty()) {
            return;
        }

        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2);
            if (keyValue.length == 2) {
                try {
                    String key = URLDecoder.decode(keyValue[0], StandardCharsets.UTF_8.name());
                    String value = URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8.name());

                    if ("POST".equalsIgnoreCase(parameter.getMethod())) {
                        parameter.addBodyParam(key, value);
                    } else {
                        parameter.addUrlParam(key, value);
                    }
                } catch (Exception e) {
                    // 如果解码失败，使用原始值
                    if ("POST".equalsIgnoreCase(parameter.getMethod())) {
                        parameter.addBodyParam(keyValue[0], keyValue[1]);
                    } else {
                        parameter.addUrlParam(keyValue[0], keyValue[1]);
                    }
                }
            }
        }
    }
}
